import 'package:business_plugin/business/config_business/config_business.dart';
import 'package:business_plugin/channel/business_channel.dart';
import 'package:business_plugin/utils/business_tools.dart';
import 'package:flutter/services.dart'; // 添加这一行以导入 MethodCall 类

class BusinessChannelPlugin {
  static final BusinessChannelPlugin _instance = BusinessChannelPlugin._internal();
  final MethodChannel _businessChannel = const MethodChannel(BusinessKitChannel.businessKitChannel); //adjust推送通道

  factory BusinessChannelPlugin() {
    return _instance;
  }

  BusinessChannelPlugin._internal();

  // 存储用户配置的回调
  BusinessCallback? _callback;

  // 配置插件
  void configure({
    required BusinessCallback callback,
  }) {
    _callback = callback;
    // 在实例化时立即设置方法处理器
    setupMethodHandlers();
  }

  // 设置方法处理器
  void setupMethodHandlers() {
    _businessChannel.setMethodCallHandler(_handleBusinessMethods);
  }

  // 处理从iOS发来的方法调用
  Future<void> _handleBusinessMethods(MethodCall call) async {
    switch (call.method) {
      case 'setPushToken':
        final String token = call.arguments as String;
        ConfigBusiness.deviceToken = token;
        BusinessTools.log('收到推送令牌: $token');
        break;
      case BusinessKitChannel.applicationDidBecomeActive:
        _callback?.applicationDidBecomeActive();
        BusinessTools.log('应用程序已经变为活跃状态: ${BusinessKitChannel.applicationDidBecomeActive}');
        break;
      case BusinessKitChannel.applicationDidEnterBackground:
        _callback?.applicationDidEnterBackground();
        BusinessTools.log('应用程序已经进入后台状态: ${BusinessKitChannel.applicationDidEnterBackground}');
        break;
      default:
        throw PlatformException(code: 'NotImplemented', message: '未实现的方法: ${call.method}');
    }
  }
}

// 回调接口，供app实现
abstract class BusinessCallback {
  //应用程序已经变为活跃状态
  void applicationDidBecomeActive();
  //应用程序已经进入后台状态
  void applicationDidEnterBackground();
}
